package com.qf.smartplatform.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.HashMultimap;
import com.qf.smartplatform.mapper.HumitureMapper;
import com.qf.smartplatform.pojo.Humiture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * projectName:day12_27_Test
 * author:guoLei
 * time:2022/1/10 14:35
 * description:
 */
@Controller
public class MyHumiTempHandler extends MyBaseCommandHandler {
    private ObjectMapper objectMapper;

    private HumitureMapper humitureMapper;

    private static HashMultimap<String, Humiture> humitureHashMultimap = HashMultimap.create();

    public static HashMultimap<String, Humiture> getHumitureHashMultimap() {
        return humitureHashMultimap;
    }

    @Autowired
    public void setHumitureMapper(HumitureMapper humitureMapper) {
        this.humitureMapper = humitureMapper;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        String payload = message.getPayload();
        System.err.println("温湿度处理器开始处理数据:" + payload);
        if (payload.contains("humidity") && payload.contains("temperature")) {
            CompletableFuture.runAsync(() -> {
                try {

                    Map map = objectMapper.readValue(payload, Map.class);
                    Humiture humiture = new Humiture();
                    humiture.setUploadTime(new Date());
                    humiture.setDeviceId((String) session.getAttributes().get("id"));
                    humiture.setHumidity((Double) map.get("humidity"));
                    humiture.setTemperature(((Double) map.get("temperature") - 32) / 1.8);
                    humitureHashMultimap.put((String) session.getAttributes().get("id"), humiture);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
